Length of Last Word.md

Given a string s consists of upper/lower-case alphabets and empty space characters ' ',
return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example, Given s = "Hello World", return 5.

题目大意:求给定字符串的中最后一个不含空格字符串的长度,如果没有返回0

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/14
 * String.split(regex, limit) 方法,可用特定正则表达式分割字符串
 * 空间复杂度O(N)
 */
public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) return 0;

        String[] strings = s.split(" ");
        return strings.length > 0 ? strings[strings.length - 1].length() : 0;
    }
}
/**
 * Created by gzdaijie on 16/5/14
 * 空间复杂度O(1),时间复杂度O(K)
 */
public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.trim().length() == 0) return 0;
        s = s.trim();
        return s.length() - s.lastIndexOf(' ') - 1;
    }
}
gzdaijie            updated 2016-05-15 00:59:02

results matching ""

    No results matching ""